<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\YjButton;
use App\Models\YjUser;
use Illuminate\Http\Request;
use EasyWeChat\Factory;

class VxController extends Controller
{

    public function GetOpenId(Request $request){

        $code = $request->input('code');
        $config = config('filesystems.wx');
        $app = Factory::miniProgram($config);
        $data = $app->auth->session($code);
        if ( !isset($data['errcode'])){
            // 请求成功  判断数据库中是否有数据
            $rdata = [
                'openid' => $data['openid'],
                'session_key' => $data['session_key'],

            ];

            return toJson(20000,"获取成功",200,$rdata)  ;
        }else{
            return toJson(20003,"获取失败")  ;
        }
    }

    public function  getUserPhoneNumber(Request $request){

              // 获取手机号码
            $config = config('filesystems.wx');
            $app = Factory::miniProgram($config);
            $iv = $request->input('iv');
            $session_key = $request->input('session_key');
            $encryptedData = $request->input('encryptedData');
            $open_id = $request->input('open_id');

            try{

                $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);

            }catch (\Exception $exception){

                return toJson(20001, '手机号授权获取失败');
            }

            $data = [
                "open_id" =>$open_id,
                 "phone" =>$decryptedData['purePhoneNumber'] ,
            ] ;
            $all_open_ids = array_column(YjUser::all()->toArray(),"open_id");

            if(!in_array($open_id,$all_open_ids)) {
                YjUser::SaveNewConsultantMessage($data);

            }

            return toJson(20000, '授权成功',200,$decryptedData['purePhoneNumber']);
        }

        public function  PutPhoneStatus(){
            $open_id = \request("open_id") ;

            $message = YjUser::getMessageByOpenid($open_id) ;

            if($message){

                return toJson(20000,"数据已存在",200,$message);
            }else{
                return toJson(20001,"数据不存在") ;
            }
        }
        
         public  function  buttonStatus(){

                    $data =  YjButton::getStatus()['status'] ;
                    $message = "ohYe_4rxH0Y2_zP_wa-8b712d8S4" ;

                return toJson($data,"开启",200,$message);
        }

}
